package com.bbcare.department.plat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.SeqUtil;
import com.bbcare.department.plat.entity.Doctor;
import com.bbcare.department.plat.entity.OutPatientDuty;
import com.bbcare.department.plat.entity.OutPatientSchedule;
import com.bbcare.department.plat.entity.ScheduleDuty;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.department.plat.service.IDoctorManagerService;
import com.bbcare.department.plat.store.ibatis.IDoctorDao;
import com.bbcare.department.plat.store.ibatis.IOutPatientDutyDao;
import com.bbcare.department.plat.store.ibatis.IOutPatientScheduleDao;

@Service
public class DoctorManagerService implements IDoctorManagerService {
	
	Logger logger = Logger.getLogger(DoctorManagerService.class); 
	
	@Autowired
	private IDoctorDao doctorDao;
	
	@Autowired
	private IOutPatientDutyDao outPatientDutyDao;
	@Autowired
	private IOutPatientScheduleDao outPatientScheduleDao;
	
	@Autowired
	private IBsStaticParamService bsStaticParamService;
	/**
	 * 查询医生基本信息主方法
	 * @param arg
	 * @return
	 * @throws Exception 
	 */
    public Doctor getDoctorById(Map<String,Object> map) throws Exception {
        logger.info("in getDoctorById----arg==");
        Map<String,Object> doctoroMap = new HashMap<String,Object>();
        doctoroMap.put("id", map.get("id"));
        Doctor doctor =doctorDao.selectById(doctoroMap);
//      DepartmentBasic departmentBasic = new DepartmentBasic();
//      org.apache.commons.beanutils.BeanUtils.populate(departmentBasic, map); 
        logger.info(JSON.toJSON(doctor));
        return doctor;
    }
    
    /**
     * 创建和更新医生基本信息
     */
    @Transactional
    public String doctorModify(Doctor doctor) throws Exception{
    	logger.info("in doctorModify----arg==" );
    	if(StringUtils.isEmpty(doctor.getId())){
    		doctor.setId(SeqUtil.getSeqNo());
    		doctor.setCreateTime(DateUtil.getSysDateA());
    		doctorDao.save(doctor);
    	}else{
    		doctor.setUpdateTime(DateUtil.getSysDateA());
    		doctorDao.update(doctor);
    	}
        return doctor.getId();
    }


	@Override
	public List<Doctor> getDoctorsByDeptId(String deptId) throws Exception {
		logger.info("in getDoctorsByDeptId----arg==" + deptId);
        List<Doctor> doctors =  doctorDao.selectByDepId(deptId);
        logger.info("out getDoctorsByDeptId----arg==");
        return doctors;
	}

	@Override
	public int deleteDoctorByIds(List<String> list) throws Exception {
		logger.info("in deleteDoctorByIds");
        int i =  doctorDao.deleteyIds(list);
        logger.info("out deleteDoctorByIds");
        return i;
	}
	
	@Override
	public int deleteScheduleByIds(List<String> list) throws Exception {
		logger.info("in deleteDoctorByIds");
		int i = outPatientDutyDao.deleteyIds(list);
        i = outPatientScheduleDao.deleteyIds(list);
        logger.info("out deleteDoctorByIds");
        return i;
	}
	
	@Override
	public int deleteAllSchedule(Map<String,Object> map) throws Exception {
		logger.info("in deleteAllSchedule");
		List<Map<String,String>> list = outPatientScheduleDao.selectShedulesByConditions(map);
		List<String> scheduleIdlist= new ArrayList<String>();
		if(!CollectionUtils.isEmpty(list)){
			for(int i =0;i<list.size();i++){
				String scheduleId = list.get(i).get("ID");
				scheduleIdlist.add(scheduleId);
			}
			outPatientDutyDao.deleteyIds(scheduleIdlist);
		}
        logger.info("out deleteAllSchedule");
        return 0;
	}

	@Override
	public List<Doctor> getDoctorsByCondition(Map<String,Object> paramMap)
			throws Exception {
		logger.info("in deleteDoctorByIds");
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 20;
		Object doctorNameObject = paramMap.get("doctorName");
		Object doctorName = (doctorNameObject!=null &&!StringUtils.isEmpty(doctorNameObject)) ? "%"+doctorNameObject.toString()+"%" : doctorNameObject ; 

		paramMap.put("doctorName",doctorName);
		paramMap.put("page", page);
		paramMap.put("rows", rows);
		
		List<Doctor> doctors=  doctorDao.selectByCondition(paramMap);
        logger.info("out deleteDoctorByIds");
		return doctors;
	}
	
	@Override
	public Integer getDoctorCountByDeptId(Map<String,Object> paramMap) throws Exception{
		logger.info("in getDoctorCountByDeptId");
		Integer count =  doctorDao.countByDepId(paramMap);
        logger.info("out getDoctorCountByDeptId");
		return count;
	}

	@Override
	@Transactional
	public String doctorScheduleModify(ScheduleDuty scheduleDuty,String createAuthor) throws Exception {
		if(null != scheduleDuty){
			OutPatientDuty duty = null;
			OutPatientSchedule schedule = new OutPatientSchedule();
			
			boolean addOpt = false; //随访新增  修改   先删除 再插入
			String scheduleId = scheduleDuty.getScheduleId();
			
			String sysdate = DateUtil.getSysDateA();
			String workDay = scheduleDuty.getWorkDay();
			String workPeriod = scheduleDuty.getWorkPeriod();
			
			if(StringUtils.isEmpty(scheduleId) ){
				//且该时段和日期 没有计划 以防前端漏传
				Map<String,String> map = new HashMap<String,String>();
				map.put("deptId",scheduleDuty.getDeptId());
				map.put("workDay",workDay);
				map.put("workPeriod",workPeriod);
				OutPatientSchedule oldSchedule = outPatientScheduleDao.selectByCondition(map);
				if(null != oldSchedule){
					scheduleId =oldSchedule.getId(); 
				}else{
					addOpt = true;
					scheduleId = SeqUtil.getSeqNo();
				}
			}
			
			schedule.setId(scheduleId);
			schedule.setWorkDay(workDay);
			schedule.setWorkPeriod(workPeriod);
			schedule.setCreateAuthor(createAuthor);
			schedule.setCreateTime(sysdate);
			schedule.setDeptId(scheduleDuty.getDeptId());
			schedule.setUpdateTime(sysdate);
			
			List<OutPatientDuty> dutyList = new ArrayList<OutPatientDuty>();
			List<Map<String,String>> list = scheduleDuty.getDoctorIds();
			
			if(CollectionUtils.isEmpty(list)){
				return null;//没有传医生 不用排值班计划
			}
			
			Map<String,String> map =null;
			
			for(int i =0;i<list.size();i++){
				map = list.get(i);
				String doctorId = map.get("doctorId");
				String workType = map.get("workType");
				if(!StringUtils.isEmpty(doctorId) && !StringUtils.isEmpty(workType)){
					duty = new OutPatientDuty();
					duty.setId(SeqUtil.getSeqNo());
					duty.setDoctorId(doctorId);
					duty.setCreateTime(sysdate);
//					duty.setRemark("");
					duty.setType(workType);
					duty.setCreateAuthor(createAuthor);
					duty.setScheduleId(scheduleId);
					dutyList.add(duty);
				}
			}
			
			if(addOpt){//新增  
				outPatientScheduleDao.save(schedule);
			}else{
				//值班先删除 再增加
				List<String> ids = new ArrayList<String>();
				ids.add(scheduleId);
				outPatientDutyDao.deleteyIds(ids);
			}
			
			if(!CollectionUtils.isEmpty(dutyList)){
				outPatientDutyDao.save(dutyList);
			}
			return scheduleId;
		}
		return null;
	}

	@Override
	public List<ScheduleDuty> getScheduleSByCondition(
			Map<String,Object> paramMap) throws Exception {
		logger.info("in getScheduleSByCondition args="+paramMap);
		
		Map<String,Object> workTypeParam = new HashMap<String,Object>();
        workTypeParam.put("deptId",paramMap.get("deptId"));
        workTypeParam.put("type",Constants.SCHEDULE_TYPE_CODE);
        Map<String,String> mapTemp = bsStaticParamService.getStaticParamsForMap(workTypeParam);
		
		List<ScheduleDuty>  scheduledutys = new ArrayList<ScheduleDuty>();
		
		List<Map<String,String>> list = outPatientScheduleDao.selectShedulesByConditions(paramMap);
		
		Map<String,String> temMap = null;
		ScheduleDuty scheduleDuty = null;
		Map<String,ScheduleDuty> map = new HashMap<String,ScheduleDuty>();
		
		for(int i =0;i<list.size();i++){
			temMap = list.get(i);
			String id = temMap.get("ID");
			String workDay = temMap.get("WORKDAY");
			String workPeriod = temMap.get("WORKPERIOD");
			String doctorId = temMap.get("DOCTORID");
			String type = temMap.get("TYPE");
			String deptId = temMap.get("deptId");
			String doctorName = temMap.get("doctorName");
			
			Map<String,String> docmap = new HashMap<String,String>();
			docmap.put("doctorId", doctorId);
			docmap.put("workType", type);
			docmap.put("doctorName", doctorName);
			docmap.put("workTypeName", mapTemp.get(type));
//			docmap.put("deptId", deptId);
			if(map.containsKey(id)){
				map.get(id).getDoctorIds().add(docmap);
			}else{
				scheduleDuty =  new ScheduleDuty();
				List<Map<String,String>> doctorIds = new ArrayList<Map<String,String>>();
				doctorIds.add(docmap);
				scheduleDuty.setDoctorIds(doctorIds);
				scheduleDuty.setScheduleId(id);
				scheduleDuty.setWorkDay(workDay);
				scheduleDuty.setWorkPeriod(workPeriod);
				scheduleDuty.setDeptId(deptId);
				map.put(id,scheduleDuty);
			}
		}
		
		scheduledutys.addAll(map.values());
		logger.info("out getScheduleSByCondition");
		return scheduledutys;
	}

}
